// pages/login/login.js
import {
  toast
} from '@/utils/extend'

import {
  reqLogin,
  reqIsRegister,
  reqGetInfo
} from '@/api/user'

import {
  setStorage,
  getStorage
} from '@/utils/storage'

import * as introduceApi from '@/api/introduce'

// 导入 ComponentWithStore 方法
import {
  ComponentWithStore
} from 'mobx-miniprogram-bindings'

// 导入 store 对象
import {
  InfoStore
} from '@/stores/InfoStore'

import dayjs from 'dayjs'
const appInstance = getApp()
ComponentWithStore({
  data: {
    isRegister: true, //判断用户是否已经报名
    wxForm: {},
    phoneForm: {},
    openId: '',
    code: ''
  },
  // 让 页面 和 Store 对象建立关联
  storeBindings: {
    store: InfoStore,
    fields: ['token', 'isRegister','userInfo'],
    actions: ['setToken', 'setisRegister', 'setUserInfo']
  },

  methods: {

    // 授权登录
    login() {
      // 使用 wx.login 获取用户的临时登录凭证 code
      wx.login({
        success: async ({
          code
        }) => {
          if (code) {
            console.log(code)
            const {
              data
            } = await reqLogin(code)
            console.log(data)

            setStorage('token', data)
            this.setToken(data)

            introduceApi.getGroup().then(res => {
              const newArray = res.data.filter(item => item.name !== '项目组').map(item => item.name)
              setStorage('group', newArray)
            })
            
            this.getUserInfo()

            this.reqIfRegister()

            wx.switchTab({
              url: '/pages/index/index',
            })
          } else {
            toast({
              title: '授权失败，请重新授权'
            })
          }
        }
      })
    },

    // 获取用户信息
    async getUserInfo() {
      const {
        data
      } = await reqGetInfo()
      console.log(data)
      // 将用户信息存储到本地
      setStorage('userInfo', data)
      // 将用户信息存储到 Store 对象
      this.setUserInfo(data)
    },
    //请求用户是否已经报名
    async reqIfRegister() {
      if (getStorage("token")) {
        const {
          data
        } = await reqIsRegister()
        if (data === '未报名') {
          this.setData({
            isRegister: false
          })
        } else {
          this.setData({
            isRegister: true
          })
          this.setUserInfo()
        }
        setStorage('isRegister', this.data.isRegister)
        this.setisRegister(this.data.isRegister)
      }
    },
  }
})